//
//  ST_EditMyIntroViewController.swift
//  btvideo
//
//  Created by JarvanZhang on 2020/2/4.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import HandyJSON

//个人介绍-Controller
class ST_EditMyIntroViewController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.title_nav_btn.setTitleForAllStates("填写个人介绍")
        
        set_up_right_btn()
        
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.bottom.left.right.equalToSuperview()
            make.top.equalTo(own_navigation_bar.snp.bottom)
        }
        
        scrollView.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
            make.width.equalToSuperview()
            make.height.equalTo(ScreenHeight-statusBarHeight-44+2)
        }
        
     
        root_view.addSubview(textView)
        root_view.addSubview(counter_label)
        counter_label.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-20)
            make.bottom.equalToSuperview().offset(-73-BTSafeAreaBottom)
            make.height.equalTo(UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular).lineHeight)
            make.width.equalTo(80)
        }
        
        
        
        
        textView.snp.makeConstraints { (make) in
            make.top.equalTo(own_navigation_bar.snp.bottom).offset(11)
            make.right.equalToSuperview().offset(-15)
            make.left.equalToSuperview().offset(15)
            make.bottom.equalTo(counter_label.snp.top).offset(-11)
        }
        
        
        root_view.addSubview(placeholderLabel)
        placeholderLabel.snp.makeConstraints { (make) in
            make.left.equalTo(textView).offset(15)
            make.right.equalTo(textView).offset(-15)
            make.top.equalTo(textView).offset(20)
        }
        
        root_view.addSubview(bottom_view)
        bottom_view.snp.makeConstraints { (make) in
            make.left.right.equalTo(textView)
            make.height.equalTo(bottom_view_height)
            make.bottom.equalToSuperview().offset(-15-BTSafeAreaBottom)
        }
        
        
        bottom_view.addSubview(look_other_btn)
        look_other_btn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(7)
            make.top.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(40)
        }
        
        bottom_view.addSubview(exampleLabel)
        exampleLabel.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(example_label_edge)
        }
        
        
        root_view.addSubview(switch_example_btn)
        switch_example_btn.snp.makeConstraints { (make) in
            make.bottom.equalTo(bottom_view.snp.top).offset(-5)
            make.height.equalTo(25)
            make.width.equalTo(60)
            make.right.equalToSuperview().offset(-15)
        }
        
        add_notification()
        
        request_data()
        
        
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        print("")
    }
    
    fileprivate var attriStringArray = [NSAttributedString]()
    
    fileprivate func request_data(){
        
        JVrequest(PH.getIntroTmpApi, success: { (json) in
            
            print("打样22:",json)
            
            for item in json["data"].arrayValue{
                
                let str = item["intro"].stringValue
                
                let attrString = NSMutableAttributedString(string: str)
                
                let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.38, green: 0.4, blue: 0.44, alpha: 1)]
                
                attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
                
                self.attriStringArray.append(attrString)
            }
            
            
            if let str = self.attriStringArray.first{
                self.exampleLabel.attributedText = str
            }
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
        }
        
    }
    
    
    fileprivate func set_up_right_btn(){
        
        right_nav_btn.setTitleForAllStates("完成")
        right_nav_btn.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.semibold)
        right_nav_btn.backgroundColor = Color.init(hexString: "#FEC207")
        right_nav_btn.cornerRadius = 15
        right_nav_btn.snp.remakeConstraints { (make) in
            make.right.equalTo(own_navigation_bar).offset(-15)
            make.centerY.equalTo(title_nav_btn)
            make.width.equalTo(60)
            make.height.equalTo(30)
        }
        right_nav_btn.isHidden = false
        
    }
    
    func layout_display_example(){
        
        guard let attrText = exampleLabel.attributedText else { return }
        
        let exampleHeigt = attrText.height(withConstrainedWidth: ScreenWidth - example_label_edge.left - example_label_edge.right - 15 * 2)
        
        let bottomHeight = exampleHeigt + example_label_edge.top + example_label_edge.bottom
        
        
        bottom_view.snp.updateConstraints { (make) in
            make.height.equalTo(bottomHeight)
            make.bottom.equalToSuperview().offset(-15-BTSafeAreaBottom)
        }
        
        switch_example_btn.isHidden = false
        exampleLabel.isHidden = false
        counter_label.snp.updateConstraints { (make) in
            make.bottom.equalToSuperview().offset(-64-bottomHeight-15-BTSafeAreaBottom)
        }
        
        
    }
    
    fileprivate func add_notification(){
        
        NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: OperationQueue.main) {[weak self] (notification) in
            
            self?.key_broad_height_changed(notification: notification)
            
        }
        
        NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: OperationQueue.main) {[weak self] (notification) in
            
            guard let strongSelf = self else{
                return
            }
            
            strongSelf.display_keybroad = false
            
            if strongSelf.display_example_hidden_keybroad{
                
                strongSelf.layout_display_example()
                
                strongSelf.display_example_hidden_keybroad = false
                
                return
            }
            
            strongSelf.exampleLabel.isHidden = true
            strongSelf.switch_example_btn.isHidden = true
            strongSelf.bottom_view.snp.updateConstraints { (make) in
                make.height.equalTo(strongSelf.bottom_view_height)
                make.bottom.equalToSuperview().offset(-15-BTSafeAreaBottom)
            }
            strongSelf.counter_label.snp.updateConstraints { (make) in
                make.bottom.equalToSuperview().offset(-73-BTSafeAreaBottom)
            }
            
        }
        
    }
    
//    MARK:- public Properties
    var display_text = ""
    
    var update_value_closure:((String)->())?

//    MARK:- Properties
    fileprivate lazy var scrollView:UIScrollView = {
       let control = UIScrollView()
        control.backgroundColor = .white
        control.delegate = self
        return control
    }()
    
    
    fileprivate lazy var root_view:UIView = {
       let control = UIView()
        control.backgroundColor = .white
        return control
    }()
    
    fileprivate lazy var display_keybroad = false
    
    fileprivate lazy var textView:UITextView = {
        let control = UITextView()
        control.textColor = UIColor.init(hexString: "#333333")
        control.tintColor = UIColor.init(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        control.cornerRadius = 10
        control.borderColor = UIColor.init(hexString: "#F2F4F7")
        control.borderWidth = 1
        control.textContainerInset = UIEdgeInsets.init(top: 20, left: 15, bottom: 20, right: 15)
        control.text = display_text
        control.delegate = self
        return control
    }()
    
    fileprivate lazy var placeholderLabel:UILabel = {
        
        let control = UILabel()
//        control.backgroundColor = Color.random
        
        control.numberOfLines = 0
        
        let attrString = NSMutableAttributedString(string: "【可以尝试从以下几个方面介绍自己】\n·工作/学习内容\n·生活日常\n·性格\n·兴趣爱好\n·想要认识的人\n* 不可以填写其他SNS的ID哦")
        
        let parag = NSMutableParagraphStyle()
        
        parag.lineSpacing = 5
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1),NSAttributedString.Key.paragraphStyle:parag]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        control.attributedText = attrString
        
        control.isHidden = display_text.count > 0
        return control
    }()
    
    fileprivate lazy var counter_label:UILabel = {
        let control = UILabel()
        
        var count = 800 - display_text.count
        if count < 0{
            count = 0
        }
        control.text = "还有\(count)字"
        control.textColor = UIColor.init(hexString: "#ACB4C0")
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        
        
        
        return control
    }()
    
    fileprivate lazy var bottom_view_height = 40.cgFloat
    
    fileprivate lazy var bottom_view:UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.init(hexString: "#F2F4F7")
        control.cornerRadius =  10
        return control
    }()
    
    fileprivate lazy var look_other_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.contentHorizontalAlignment = .left
        control.setImageForAllStates(ST_ImageUtils.imageName("个人中心_icon_查看")!)
        control.setTitleForAllStates("看看别人怎么写  ")
        control.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 0)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        control.setTitleColorForAllStates(UIColor.init(hexString: "#333333")!)
        control.add_touch_up(insideTarget: self, action: #selector(look_other_handle))
        return control
    }()
    
    fileprivate let example_label_edge = UIEdgeInsets.init(top: 47, left: 31, bottom: 15, right: 13)
    
    fileprivate lazy var exampleLabel:UILabel = {
        let control = UILabel()
        control.numberOfLines = 0
        control.isHidden = true
        return control
    }()
    
    fileprivate var display_example_hidden_keybroad = false
    
    fileprivate lazy var switch_example_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = Color.init(hexString: "#F2F4F7")
        control.cornerRadius = 12
        control.setTitleForAllStates("换一个")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.semibold)
        control.setTitleColorForAllStates(UIColor.init(hexString: "#61666F")!)
        control.add_touch_up(insideTarget: self, action: #selector(switch_example_handle))
        control.isHidden = true
        return control
    }()
    
    fileprivate var currentIdx = 0
    
    fileprivate var maxCount = 800
    
    override func right_click() {
        
        if self.textView.text.isEmpty{
            return
        }
        
        display_text = self.textView.text
        
        if display_text != ""{
            ST_PinterestHomeGuidanceManager.shared.hidden_add_intro()
        }
        
        
        self.update_value_closure?(display_text)
        
        goback_previous_controller()
    }
    
    
}

//MARK: - Keybroad Event
extension ST_EditMyIntroViewController{
    
    func key_broad_height_changed(notification:Notification){
        
        self.display_keybroad = true
        
        if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
            
            let keyboardRectangle = keyboardFrame.cgRectValue
            
            let keyboard_height = keyboardRectangle.height
            
            //            if #available(iOS 11.0, *) {
            //                let bottomInset = self.view.safeAreaInsets.bottom
            //                keyboard_height -= bottomInset
            //            }
            //            print("iPhone X 键盘",keyboard_height)
            
            self.exampleLabel.isHidden = true
            self.switch_example_btn.isHidden = true
           
            self.bottom_view.snp.updateConstraints { (make) in
                make.height.equalTo(bottom_view_height)
                make.bottom.equalToSuperview().offset(-15-keyboard_height)
            }
            counter_label.snp.updateConstraints { (make) in
                make.bottom.equalToSuperview().offset(-73-keyboard_height)
            }
            
        }
    }
    
    
}

//MARK: - Event
extension ST_EditMyIntroViewController{
    
    
    
    @objc func switch_example_handle(){
        
        
        currentIdx += 1
        let idx = currentIdx % attriStringArray.count
        if let str = attriStringArray[safe:idx]{
            exampleLabel.attributedText = str
        }
        
        layout_display_example()
        
    }
    
    
    @objc func look_other_handle(){
        
        if !self.display_keybroad{
            
            layout_display_example()
            
            return
        }
        
        if display_example_hidden_keybroad{
            return
        }
        
        display_example_hidden_keybroad = true
        
        self.textView.endEditing(true)
        
        
        
        
    }
    
}


extension ST_EditMyIntroViewController:UITextViewDelegate{
    
    func textViewDidChange(_ textView: UITextView) {
        placeholderLabel.isHidden = !textView.text.isEmpty
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        /* 这个方案暂时不行 bug
        if text == UIPasteboard.general.string{
         
            let currentString: NSString = textView.text! as NSString
            
            let newString: NSString =
                currentString.replacingCharacters(in: range, with: text) as NSString
            
            if newString.length > maxCount{
                
                let mutableStr = NSMutableString.init(string: newString)
                
                mutableStr.deleteCharacters(in: NSRange.init(location: maxCount - 1, length: newString.length - maxCount))
                
                
            }
            return true
        }
        */
        
        guard var animal = textView.text else{
            return true
        }
        
        if let idxRange = Range.init(range, in: animal){
            
            animal.replaceSubrange(idxRange, with: text)
            
            var residueCount = maxCount - animal.count
            
            if residueCount < 0{
                residueCount = 0
            }
            
            counter_label.text = "还有\(residueCount)字"
            
            return animal.count <= maxCount
            
        }else{
            return true
        }
        
        
        
    }
}


extension ST_EditMyIntroViewController:UIScrollViewDelegate{
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView == self.scrollView{
            self.textView.endEditing(true)
        }
    }
    
}
